﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;

namespace ufs.node
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<NodeConfig>(Configuration.GetSection("ufsNode"));
            services.AddSingleton<ThumbnailMiddleware>();
            services.AddSingleton<UploadFileMiddleware>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IOptions<NodeConfig> config)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var provider = new FileExtensionContentTypeProvider();
            if (config.Value.MimeModifiers != null && config.Value.MimeModifiers.Length > 0)
            {
                foreach (var mimeModifer in config.Value.MimeModifiers)
                {
                    if (string.IsNullOrWhiteSpace(mimeModifer.Ext))
                    {
                        continue;
                    }

                    switch (mimeModifer.Opt)
                    {
                        case MimeModiferOpts.add:
                        {
                            if (!string.IsNullOrWhiteSpace(mimeModifer.Type))
                            {
                                provider.Mappings[mimeModifer.Ext] = mimeModifer.Type;
                            }

                            break;
                        }
                        case MimeModiferOpts.remove:
                            provider.Mappings.Remove(mimeModifer.Ext);
                            break;
                    }
                }
            }

            //生成缩略图
            if (config.Value.EnableThumbnail)
            {
                app.UseWhen(
                    context => context.Request.Path.StartsWithSegments(config.Value.VirtualPath,
                        StringComparison.OrdinalIgnoreCase),
                    appBuilder => { appBuilder.UseMiddleware<ThumbnailMiddleware>(); });
            }

            //访问
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(config.Value.PhysicalPath),
                RequestPath = config.Value.VirtualPath,
                ContentTypeProvider = provider,
                OnPrepareResponse = (ctx) =>
                {
                    ctx.Context.Response.Headers.Append("Cache-Control",
                        $"public, max-age={config.Value.CachePeriod}");
                },
            });

            app.UseWhen(
                context => context.Request.Path.StartsWithSegments("/uploadfile",
                    StringComparison.OrdinalIgnoreCase),
                appBuilder => { appBuilder.UseMiddleware<UploadFileMiddleware>(); });

            //访问根目录
            app.UseWhen(context => context.Request.Path.Value.Equals("/"),
                builder => builder.Run(async ctx => { await ctx.Response.WriteAsync("Hello ufsNode!"); }));

            app.Run(async context =>
            {
                context.Response.StatusCode = 404;
                await context.Response.WriteAsync("not found:" + context.Request.Path.Value);
            });
        }
    }
}